package com.caigou.modules.article.ui

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import cc.shinichi.library.ImagePreview
import cn.bingoogolapple.bgabanner.BGABanner
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.screenCapture
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.utils.MediaUtils
import com.caigou.comm.base.viewmodel.FollowViewModel
import com.caigou.comm.base.viewmodel.ReportViewModel
import com.caigou.comm.base.widget.ReportDialog
import com.caigou.modules.article.R
import com.caigou.modules.article.adpter.ArticlePagerAdapter
import com.caigou.modules.article.bean.ArticleItemBean
import com.caigou.modules.article.databinding.ActivityArticleBinding
import com.caigou.modules.article.ui.fragment.ArticleCommentFragment
import com.caigou.modules.article.ui.fragment.MoreArticleFragment
import com.caigou.modules.article.viewmodel.ArticleViewModel
import com.caigou.modules.article.viewmodel.LikeViewModel
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/11/21
 */
@Route(path = RouterPath.Article.PAGE_ARTICLE)
@AndroidEntryPoint
class ArticleActivity : BaseActivity() {

    private lateinit var binding: ActivityArticleBinding

    private val articleViewModel: ArticleViewModel by viewModels()
    private val likeViewModel: LikeViewModel by viewModels()
    private val followViewModel: FollowViewModel by viewModels()
    private val reportViewModel: ReportViewModel by viewModels()

    @Autowired(name = AppConstants.ARTICLE_ITEM_BEAN)
    lateinit var articleItemBean: ArticleItemBean

    @JvmField
    @Autowired(name = AppConstants.DATA_ID)
    var dataId = 0

    private val itemNames = mutableListOf(
        "全部评论",
        "更多作品"
    )

    private val fragments = mutableListOf<Fragment>(
        ArticleCommentFragment(),
        MoreArticleFragment()
    )

    private val pagerAdapter: ArticlePagerAdapter by lazy {
        ArticlePagerAdapter(this)
    }


    private val bannerAdapter: BGABanner.Adapter<ImageView, String> by lazy {
        BGABanner.Adapter<ImageView, String> { banner, itemView, feedImageUrl, position ->
            ImageLoader.load(this, feedImageUrl, itemView)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityArticleBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.articleLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        binding.articleSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                fetchArticleInfo()
            }
        }
        pagerAdapter.setList(fragments)
        binding.articleViewPager2.adapter = pagerAdapter
        binding.articleViewPager2.isUserInputEnabled = false
        TabLayoutMediator(binding.articleTabLayout, binding.articleViewPager2, true, true) { tab, position ->
            tab.text = itemNames[position]
        }.attach()
        binding.articleViewPager2.offscreenPageLimit = itemNames.size
        binding.articleViewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                val view = fragments[position].view
                view?.let {
                    updatePagerHeightForChild(it, binding.articleViewPager2)
                }
            }
        })


        binding.articleIvBack.setOnClickListener {
            finish()
        }

        binding.articleLlLlShare.setOnClickListener {
            val bitmap = binding.articleLlContainer.screenCapture()
            MediaUtils.saveBitmap(this, bitmap)
            showToast("截图已保存到系统相册")
        }


        LiveDataBus.get().with(BusKey.LOAD_VP2_FINISH, Any::class.java).observe(this) {
            fragments[binding.articleViewPager2.currentItem].view?.apply {
                updatePagerHeightForChild(this, binding.articleViewPager2)
            }
        }

        LiveDataBus.get().with(BusKey.REPLY_SUCCESS, Any::class.java).observe(this) {
            (fragments[0] as ArticleCommentFragment).loadCommentList()
        }

        fetchArticleInfo()
    }


    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        ev?.let {
            if (it.action == MotionEvent.ACTION_DOWN) {
                val v = currentFocus
                if (isShouldHideInput(v, it)) {
                    val imm = this@ArticleActivity.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(v!!.windowToken, 0)
                }
                return super.dispatchTouchEvent(it)
            }
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return if (window.superDispatchTouchEvent(ev)) {
            true
        } else onTouchEvent(ev)
    }

    override fun onBackPressed() {
        if (fragmentStack.isNotEmpty() && fragmentStack.size > 1) {
            fragmentStack.removeLast()
            switchFragment(fragmentStack.last)
        } else {
            super.onBackPressed()
        }
    }

    override fun observeViewModel() {
        observe(articleViewModel.articleInfoLiveData, ::handleGetArticleInfo)
        observe(articleViewModel.articleCollectLiveData, ::handleSetCollect)
        observe(followViewModel.followLiveData, ::handleSetFollow)
        observe(likeViewModel.articleLikeLiveData, ::handleSetArticleLike)
        observe(reportViewModel.postReportLiveData, ::handleSetReport)
    }

    private fun handleGetArticleInfo(result: Resource<ArticleItemBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.articleSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取评论信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.articleSwipeRefreshLayout.isRefreshing = false

                if (result.data == null) {
                    return
                }
                articleItemBean = result.data!!
                handleArticleInfo(result.data!!)
                (fragments[0] as ArticleCommentFragment).loadCommentList()
                (fragments[1] as MoreArticleFragment).fetchMoreArticleList()
            }
        }
    }

    private fun handleSetArticleLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                    fetchArticleInfo()
                }
            }
        }
    }

    private fun handleSetCollect(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("收藏失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                    fetchArticleInfo()
                }
            }
        }
    }

    private fun handleSetFollow(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("关注失败，请稍后再试")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data != null) {
                    showToast(result.data!!)
                    fetchArticleInfo()
                }
            }
        }
    }

    private fun handleSetReport(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("举报异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
            }
        }
    }

    private fun fetchArticleInfo() {
        if (AppBackgroundInfo.instance.hasLogin) {
            articleViewModel.getArticleInfo(AppBackgroundInfo.instance.userBean!!.userId, dataId)
        } else {
            articleViewModel.getArticleInfo("", dataId)
        }
    }

    private fun handleArticleInfo(bean: ArticleItemBean) {
        if (TextUtils.isEmpty(bean.userInfo.headImg)) {
            binding.articleIvAuthorAvatar.setImageResource(R.drawable.img_comm_avatar)
        } else {
            ImageLoader.loadCircle(this, bean.userInfo.headImg, binding.articleIvAuthorAvatar)
        }

        if (AppBackgroundInfo.instance.hasLogin) {
            if (TextUtils.isEmpty(AppBackgroundInfo.instance.userBean!!.headImg)) {
                binding.articleIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this, AppBackgroundInfo.instance.userBean!!.headImg, binding.articleIvMyAvatar)
            }
        } else {
            binding.articleIvMyAvatar.setImageResource(R.drawable.img_comm_avatar)
        }

        binding.articleTvAuthorNickname.text = bean.userInfo.nickName

        if (bean.concern) {
            binding.articleBtnFocus.text = "已关注"
            binding.articleBtnFocus.setBackgroundResource(R.drawable.comm_btn_red_white)
            binding.articleBtnFocus.setTextColor(Color.parseColor("#FE6880"))
        } else {
            binding.articleBtnFocus.text = "+关注"
            binding.articleBtnFocus.setBackgroundResource(R.drawable.comm_btn_red)
            binding.articleBtnFocus.setTextColor(Color.parseColor("#FFFFFF"))
        }
        binding.articleBtnFocus.setOnClickListener {
            if (!AppBackgroundInfo.instance.hasLogin) {
                showToast("请先登录")
                return@setOnClickListener
            }
            followViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, bean.userInfo.userId)
        }

        binding.articleIvReport.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                with(ReportDialog(this)) {
                    btnConfirm.setOnClickListener {
                        if (TextUtils.isEmpty(reportCause)) {
                            showToast("举报原因不能为空！")
                            return@setOnClickListener
                        }
                        reportViewModel.setPostReport(AppBackgroundInfo.instance.userBean!!.userId, bean.userInfo.userId, reportCause, bean.dataId, 2)
                        dismiss()
                    }
                    show()
                }
            } else {
                ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
            }
        }

        binding.articleBanner.run {
            setIsNeedShowIndicatorOnOnlyOnePage(false)
            setAutoPlayAble(false)
            setData(bean.imgs, null)
            setAdapter(bannerAdapter)
            setDelegate { _, _, _, position ->
                showPreviewDialog(bean.imgs, position)
            }
        }

        binding.articleTvTitle.text = bean.title
        binding.articleTvDesc.text = bean.content
        binding.articleTvCreateTime.text = "发布时间：${bean.createTime}"
        binding.articleTvBrowseCount.text = "阅读量：${bean.browseCount}"


        if (bean.favorite) {
            binding.articleIvCollect.setImageResource(R.drawable.img_article_collected)
            binding.articleTvCollect.setTextColor(Color.parseColor("#FE6880"))
        } else {
            binding.articleIvCollect.setImageResource(R.drawable.img_article_collect)
            binding.articleTvCollect.setTextColor(Color.parseColor("#505050"))
        }

        if (bean.like) {
            binding.articleIvLike.setImageResource(R.drawable.img_article_like)
            binding.articleTvLike.setTextColor(Color.parseColor("#FE6880"))
        } else {
            binding.articleIvLike.setImageResource(R.drawable.img_article_unlike)
            binding.articleTvLike.setTextColor(Color.parseColor("#505050"))
        }

        binding.articleLlLike.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                if (bean.like) {
                    showToast("您已经点过赞了")
                } else {
                    likeViewModel.setArticleLike(bean.dataId, AppBackgroundInfo.instance.userBean!!.userId, bean.userInfo.userId)
                }
            } else {
                showToast("请您先登录")
            }
        }

        binding.articleBtnReply.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance()
                    .build(RouterPath.Article.PAGE_ARTICLE_REPLY)
                    .withObject(AppConstants.ARTICLE_ITEM_BEAN, bean)
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }

        binding.articleIvAuthorAvatar.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_PAGE)
                    .withString(AppConstants.USER_ID, bean.userInfo.userId)
                    .navigation()
            }
        }
    }

    private fun showPreviewDialog(urls: MutableList<String>, pos: Int) {
        ImagePreview.getInstance().setContext(this)
            .setIndex(pos)
            .setImageList(urls)
            .setZoomTransitionDuration(300)
            .setShowErrorToast(true)
            .setShowCloseButton(true)
            .setShowDownButton(true)
            .start()

    }

    private fun updatePagerHeightForChild(view: View, pager: ViewPager2) {
        view.post {
            val wMeasureSpec = View.MeasureSpec.makeMeasureSpec(view.width, View.MeasureSpec.EXACTLY)
            val hMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            view.measure(wMeasureSpec, hMeasureSpec)
            if (pager.layoutParams.height != view.measuredHeight) {
                pager.layoutParams = (pager.layoutParams).also { lp ->
                    lp.height = view.measuredHeight
                }
            }
        }
    }
}